package org.lagou.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lagou.Dao.CompanyDao;
import org.lagou.Dao.ResumeDao;
import org.lagou.Dao.UserDao;
import org.lagou.Dao.impl.CompanyDaoImpl;
import org.lagou.Dao.impl.ResumeDaoImpl;
import org.lagou.Dao.impl.UserDaoImpl;
import org.lagou.bean.CompanyBean;
import org.lagou.bean.ReponseBody;
import org.lagou.bean.ResumeBean;
import org.lagou.bean.UserBean;
import org.lagou.tools.Tools;

import com.google.gson.Gson;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	Gson gson = new Gson();
	UserDao udao = new UserDaoImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String t = request.getParameter("t");
		switch (t) {
		case "getUserAll":
			getUserAll(request, response);
			break;
		case "getUserPagin":
			getUserPagin(request, response);
		case "getUserCount":
			getUserCount(request, response);
			break;
		case "getByEmailUser":
			getByEmailUser(request, response);
			break;
		case "addUser":
			addUser(request, response);
			break;
		case "updateUser":
			updateUser(request, response);
			break;
		case "updatePwdById":
			updatePwdById(request, response);
			break;
		case "deleteUserById":
			deleteUserById(request, response);
			break;
		case "getUserByName1":
			getUserByName1(request, response);
			break;
		case "getUserByName2":
			getUserByName2(request, response);
			break;
		case "deleteUserByIds":
			deleteUserByIds(request, response);
			break;
		case "getUserByType":
			getUserByType(request, response);
			break;
		case "updateDelById":
			updateDelById(request, response);
			break;	
		case "getUserOutType":
			getUserOutType(request, response);
			break;
		case "addAdmin":
			addAdmin(request, response);
			break;
		case "adduser":
			adduser(request, response);
			break;
		case "updateUserName":
			updateUserName(request, response);
			break;
		default:
			break;
		}
	}

	private void updateUserName(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		// 读取session值
		String email = (String) request.getSession().getAttribute("email");
		UserDao udao = new UserDaoImpl();
		List<UserBean> ulist = udao.getByEmailUser(email);
		int userid = 0;
		for (UserBean u : ulist) {
			userid = u.getId();
		}
		String name = request.getParameter("name");
		String date = Tools.getNowDate();

		UserBean info = new UserBean(userid, name,  date);
		if (udao.updateUserName(info) > 0) {
			rb.setMsg("修改成功");
		} else {
			rb.setStatus(0);
			rb.setMsg("修改失败");
		}
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void adduser(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();
		
		String name=request.getParameter("name");
		String email = request.getParameter("email");
		String pwd = request.getParameter("pwd");
		String tel = request.getParameter("tel");
		int type = Integer.parseInt(request.getParameter("type"));
		int del=0;
		UserBean uinfo = new UserBean(name, pwd, tel, type, email, del);
		if (udao.getByEmailUser(email).isEmpty()) {
			rb.setMsg("添加成功");
			rb.setData(udao.adduser(uinfo));
		}else {
			rb.setMsg("该邮箱已被注册");
			rb.setStatus(0);
		}
		
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getUserByName2(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();
		String name = request.getParameter("name");
		int type = Integer.parseInt(request.getParameter("type"));
		rb.setData(udao.getUserByName2(name,type));
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void addAdmin(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();
		
		String name=request.getParameter("name");
		String email = request.getParameter("email");
		String pwd = request.getParameter("pwd");
		String tel = request.getParameter("tel");
		int type =3;
		int del=0;
		UserBean uinfo = new UserBean(name, pwd, tel, type, email, del);
		rb.setData(udao.addAdmin(uinfo));
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getUserOutType(HttpServletRequest request, HttpServletResponse response) {
				ReponseBody rb = new ReponseBody();
				int type = Integer.parseInt(request.getParameter("type"));
				
				int pageIndex = request.getParameter("pageIndex") == null ? 1
						: Integer.parseInt(request.getParameter("pageIndex"));
				int pageSize = request.getParameter("pageSize") == null ? 1
						: Integer.parseInt(request.getParameter("pageSize"));
				
				int count=(int)udao.getUserCount();
				rb.setStatus(count);
				rb.setData(udao.getUserOutType(type,pageIndex,pageSize));
				try {
					response.getWriter().write(gson.toJson(rb));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
	}

	private void updateDelById(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();
		
		int del=Integer.parseInt(request.getParameter("del"));
		int id=Integer.parseInt(request.getParameter("id"));
		UserBean uinfo = new UserBean(id, del);
		
		if (udao.updateDelById(uinfo)>0) {
			rb.setMsg("修改成功");
		}
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getUserByType(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		ReponseBody rb = new ReponseBody();
		int type = Integer.parseInt(request.getParameter("type"));
		rb.setData(udao.getUserByType(type));
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void getUserByName1(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();
		String name = request.getParameter("name");
		int type = Integer.parseInt(request.getParameter("type"));
		rb.setData(udao.getUserByName1(name,type));
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 删除多个用户
	private void deleteUserByIds(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		String ids = request.getParameter("ids");
		String[] idss = ids.split(",");
		for (int i = 0; i < idss.length; i++) {
			int id = Integer.parseInt(idss[i]);
			System.out.println(id);
			if (udao.deleteUserById(id) > 0) {
				rb.setMsg(idss[i] + "删除成功");
			} else {
				rb.setStatus(0);
				rb.setMsg("删除失败");
			}
		}
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void deleteUserById(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		if (request.getParameter("id") != null) {
			int id = Integer.parseInt(request.getParameter("id"));
			if (udao.deleteUserById(id) > 0) {
				rb.setMsg("删除成功");
			}
		} else {
			rb.setStatus(0);
			rb.setMsg("删除的ID不能为空");
		}

		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void updateUser(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		String tel = request.getParameter("tel");
		int type = Integer.parseInt(request.getParameter("type"));
		int state = Integer.parseInt(request.getParameter("state"));
		String email = request.getParameter("email");
		int del = Integer.parseInt(request.getParameter("del"));
		String date = Tools.getNowDate();

		UserBean info = new UserBean(id, name, pwd, tel, type, state, email, del, date);
		if (udao.updateUser(info) > 0) {
			rb.setMsg("修改成功");
		} else {
			rb.setStatus(0);
			rb.setMsg("修改失败");
		}
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getUserCount(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		rb.setData(udao.getUserCount());
		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getUserPagin(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		int pageIndex = request.getParameter("pageIndex") == null ? 1
				: Integer.parseInt(request.getParameter("pageIndex"));
		int pageSize = request.getParameter("pageSize") == null ? 1
				: Integer.parseInt(request.getParameter("pageSize"));
		rb.setData(udao.getUserPagin(pageIndex, pageSize));

		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void getUserAll(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		rb.setMsg("查询成功");
		rb.setData(udao.getUserAll());

		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * showdoc
	 * 
	 * @catalog 用户相关/修改功能
	 * @title 修改密码
	 * @description 用户修改的接口
	 * @method post
	 * @url http://localhost:8080/lagouwang/UserServlet?t=updatePwdById
	 * @return {1：成功，0：失败}
	 * @param pwd  必选 string 原密码
	 * @param pwd1 必选 string 第一次输入的新密码
	 * @param pwd2 必选 string 第二次输入的新密码
	 * @remark 邮箱号由服务器读取session值获得
	 * @number 98
	 */
	private void updatePwdById(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		// 读取session值
		String email = (String) request.getSession().getAttribute("email");
		List<UserBean> ulist = udao.getByEmailUser(email);
		if (!ulist.isEmpty()) {
			int id = 0;
			String oldpwd = null;
			for (UserBean u : ulist) {
				id = u.getId();
				oldpwd = u.getPwd();
			}
			String pwd = request.getParameter("oldPassword");
			String pwd1 = request.getParameter("newPassword");
			String pwd2 = request.getParameter("newPassword2");

			if (oldpwd.equals(pwd)) {
				if (pwd1.equals(pwd2)) {
					UserBean info = new UserBean(id, pwd1);
					udao.updatePwdById(info);
					rb.setMsg("修改成功");
					rb.setStatus(1);
				} else {
					rb.setMsg("两次输入的密码不一致");
					rb.setStatus(0);
				}
			} else {
				rb.setMsg("您输入的密码不正确");
				rb.setStatus(0);
			}
		} else {
			rb.setMsg("您没有登录");
			rb.setStatus(0);
		}

		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * showdoc
	 * 
	 * @catalog 用户相关/查询功能
	 * @title 根据邮箱查询用户信息
	 * @description 用户查询的接口
	 * @method post
	 * @url http://localhost:8080/lagouwang/UserServlet?t=getByEmailUser
	 * @return {1：成功，0：失败}
	 * @remark 邮箱号由服务器读取session值获得
	 * @number 98
	 */
	private void getByEmailUser(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		// 读取session值
		String email = (String) request.getSession().getAttribute("email");
		List<UserBean> ulist = udao.getByEmailUser(email);
		int userid=-1;
		for (UserBean u : ulist) {
			userid=u.getId();
		}

		if (!udao.getByEmailUser(email).isEmpty()) {
			rb.setMsg("查询成功");
			CompanyDao cdao=new CompanyDaoImpl();
			List<CompanyBean> clist=cdao.getCompanyByUserid(userid);
			if (!clist.isEmpty()) {
				//2表示公司已经注册了
				rb.setStatus(2);
			}else {
				//3表示公司还没有注册了
				rb.setStatus(3);
			}
			rb.setData(udao.getByEmailUser(email));
		} else {
			rb.setMsg("您未登录");
			rb.setStatus(0);
		}

		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * showdoc
	 * 
	 * @catalog 用户相关/注册功能
	 * @title 用户注册
	 * @description 用户注册的接口
	 * @method post
	 * @url http://localhost:8080/lagouwang/UserServlet?t=addUser
	 * @param email 必选 string 用户名
	 * @param pwd   必选 string 密码
	 * @param type  必选 string 用户类型
	 * @return {1：成功，0：失败}
	 * @remark 项目还在完善中
	 * @number 97
	 */
	private void addUser(HttpServletRequest request, HttpServletResponse response) {
		ReponseBody rb = new ReponseBody();

		String email = request.getParameter("email");
		String pwd = request.getParameter("pwd");
		int type = Integer.parseInt(request.getParameter("type"));
		String date = Tools.getNowDate();

		if (udao.getByEmailUser(email).isEmpty()) {
			if (udao.addUser(new UserBean(0, "lagouuser", pwd, null, type, 0, email, 0, date)) > 0) {
				int userid = 0;
				List<UserBean> ulist = udao.getByEmailUser(email);
				for (UserBean u : ulist) {
					userid = u.getId();
				}
				// 创建简历表
				ResumeDao rdao = new ResumeDaoImpl();
				ResumeBean rinfo = new ResumeBean("你的简历", userid, "lagouuser", "男","暂无",date);
				rdao.addResume(rinfo);
				rb.setMsg("注册成功请前往登录");
			} else {
				rb.setStatus(0);
				rb.setMsg("注册失败");
			}
		} else {
			rb.setStatus(0);
			rb.setMsg("该邮箱已被注册！");
		}

		try {
			response.getWriter().write(gson.toJson(rb));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
